<?php

namespace App\Admin\Renderable;

use App\Admin\Repositories\ArticleCategory;
use App\Models\AdvType;
use App\Models\Article;
use Dcat\Admin\Grid;
use Dcat\Admin\Grid\LazyRenderable;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Models\Administrator;

class ArticleTable extends LazyRenderable
{
    public function grid(): Grid
    {
        $advTypeId = $this->payload['adv_type_id'];
        $regionId = $this->payload['region_id'];
		$type = $this->payload['type']?$this->payload['type']:'';
		$types=explode(',',$type);
	 
        $advType = AdvType::find($advTypeId);
        if ($advType->category_id) {
            $allChildCategoryId = ArticleCategory::getChild($advType->category_id);
        } else {
            $allChildCategoryId = [];
//            $regionId = 0; // 首页那几个地区分类广告位内容可以选所有文章
        }
        return Grid::make(new Article(), function (Grid $grid) use ($allChildCategoryId, $regionId,$types) {
            $grid->model()->where('is_show', 1);
            if ($allChildCategoryId) {
                $grid->model()->whereIn('category_id', $allChildCategoryId);
            }
//            if ($regionId) {
//                $grid->model()->where('region_id', $regionId);
//            }

            $grid->model()->where(function ($query_region) use ($regionId) {
                $query_region->where('region_id', 0);
                $query_region->orWhere('region_id', null);
                if ($regionId > 0) {
                    $query_region->orWhere('region_id', $regionId);
                }
            });
			if(!empty($types)){
				$grid->model()->whereIn('types',$types);
			}	
            $grid->column('id', 'ID')->sortable();
            $grid->column('article_title', '文章标题');
            $grid->column('created_at');

            $grid->quickSearch(['id', 'article_title']);

            $grid->paginate(10);
            $grid->disableActions();
        });

    }
}